import utils_index from '../../utils/index.js';
const regeneratorRuntime = utils_index.regeneratorRuntime
import {
  itemModel
} from '../../apis/index.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [{
      type: false
    }],
    totalPrice:0
  },
  clickList(e) {
    let {
      list
    } = this.data
    let _this = this
    let data = utils_index.getDataSet(e)
    let object = `list[${data.index}].type`
    let type = list[data.index].type
    this.setData({
      [object]: !type,
    },()=>{
      let total = this.computeTotalPrice()
      this.setData({
        totalPrice:total
      })
    })
    console.log(this.data.list)
  },
  mixins: [require('../../myMixin.js')],
  onLoad: function(options) {
    this.data.rent_id = options.rent_id?options.rent_id:''
    this.data.uid = options.user_id?options.user_id:''
    let uid = utils_index.getStorageSync('uid')
    if(uid == this.data.uid){
      utils_index.reLaunch({
        url:'../index/index'
      })
      return false
    }
    if(!this.data.rent_id){
      utils_index.showToast('网络出错,未能获取分享数据','none')
      return false
    }
    this.getRentInfoList()
  },
  onReady: function() {

  },
  onShow: function() {

  },
  getRentInfoList(rent_id){
    utils_index.showLoading()
    itemModel.leaseInfoList({lid:this.data.rent_id}).then(res=>{
      let {avatar,name,data,id} = res.list
      data.forEach(el => {
        el.type = false
      })
       this.setData({
         avatar:avatar,
         name:name,
         list:data
       },()=>{
         utils_index.hideAll()
       })
    }).catch(()=>{
      utils_index.hideAll()
    })
  },
  computeTotalPrice(){
    let {list} = this.data
    let totalPrice = 0
    list.forEach(el => {
      if(el.type){
        totalPrice += el.price*10000
      }
    })
    totalPrice = (totalPrice/10000).toFixed(2)
    return totalPrice
  },
  requestPay(){
    let {list} = this.data
    let totalPrice = 0
    let arr = []
    list.forEach(el => {
      if(el.type){
        totalPrice += el.price*10000
        let temp = {[el.id]:el.price}

        arr.push(temp)
      }
    })
    if(totalPrice == 0){
      utils_index.showToast('请选择购买项目')
      return false
    }
    totalPrice = (totalPrice/10000).toFixed(2)

    let param = {
      lid:this.data.rent_id,
      total_price:totalPrice,
      content:JSON.stringify(arr)
    }
    itemModel.leasePrePay(param).then(res=>{
      utils_index.pay(res).then(res=>{
        if(res){
          utils_index.showToast('购买成功','success')
          setTimeout(()=>{
            utils_index.reLaunch({
              url:'../index/index'
            })
          },1500)
        }else{
          utils_index.showToast('购买失败','none')
        }
      })
    })
  },
  relaunch(){
    utils_index.reLaunch({
      url:'../index/index'
    })
  }
})